package com.admin.socketmultiplayer.activity

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import cn.bmob.v3.BmobUser
import com.admin.socketmultiplayer.R
import com.admin.socketmultiplayer.bean.MyUser
import com.bumptech.glide.Glide
import kotlinx.android.synthetic.main.activity_setting.*
import kotlinx.android.synthetic.main.layout_title.*
import org.jetbrains.anko.startActivity
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.view.View
import cn.bmob.v3.datatype.BmobFile
import cn.bmob.v3.exception.BmobException
import cn.bmob.v3.listener.UpdateListener
import cn.bmob.v3.listener.UploadFileListener
import com.admin.socketmultiplayer.config.DataUtils
import com.admin.socketmultiplayer.config.RequestCode
import com.admin.socketmultiplayer.dialog.UserInfoChangeDialog
import com.socks.library.KLog
import me.nereo.multi_image_selector.MultiImageSelectorActivity
import org.jetbrains.anko.startActivityForResult
import org.jetbrains.anko.toast
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream


/**
 * Created by 吴昶 on 2018/5/9.
 */
class SettingActivity:BaseActivity(){

    var user:MyUser?=null
    var dialog: UserInfoChangeDialog?=null
    var path=""
    var savePath= Environment.getExternalStorageDirectory().path+"/cut.png"

    override fun bindLayout(): Int {
        return R.layout.activity_setting
    }


    override fun initData(){
        tv_title.text="设置"
        iv_back.setImageResource(R.mipmap.return_normal)
        initUserInfo()
    }

    override fun onResume() {
        super.onResume()
    }

    fun initUserInfo(){
        user= BmobUser.getCurrentUser(MyUser::class.java)
        tv_user_name.text=user!!.username
        tv_user_email.text=user!!.email
        tv_user_phone.text=user!!.mobilePhoneNumber
        tv_user_qq.text=user!!.QQ
        tv_user_weichat.text=user!!.weChat
        if(user!!.header!=null){
            Glide.with(this).load(user!!.header!!.fileUrl).into(iv_user_header)
        }
    }

    override fun initEvent(){
        iv_back.setOnClickListener { finish() }
        //头像修改
        relate_user_info.setOnClickListener {
            startActivityForResult<MultiImageSelectorActivity>(RequestCode.GET_IMAGE, MultiImageSelectorActivity.EXTRA_SELECT_COUNT to 1)
        }
        //使用说明
        relate_instructions.setOnClickListener {

        }
        //客服
        relate_customer_service.setOnClickListener {
            try {
                val url = "mqqwpa://im/chat?chat_type=wpa&uin=2369740697"
                startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)))
            }catch (e:Exception){
                toast("请检查是否已按装 QQ")
            }
        }
        //切换账号
        relate_login_out.setOnClickListener {
            BmobUser.logOut()
            MyApplication.finishAllActivity()
            startActivity<LoginActivity>()
            finish()
        }

        relate_change_password.setOnClickListener {
            if(user!!.email==null||user!!.email==""){
                toast("未设置邮箱无法修改密码，请先设置邮箱")
            }else {
                startActivity<ChangePasswordActivity>()
            }
        }
        tv_user_phone.setOnClickListener(listener)
        tv_user_email.setOnClickListener(listener)
        tv_user_qq.setOnClickListener(listener)
        tv_user_weichat.setOnClickListener(listener)
    }

    var listener= View.OnClickListener {
        if(dialog==null){
            dialog= UserInfoChangeDialog(this,R.layout.dialog_user_info,R.style.cusdialog,changInfolistener)
        }
        dialog!!.show()
    }

    var changInfolistener=object :UserInfoChangeDialog.OnCancelListener{
        override fun onCancelListener(msg: String) {
            if(msg=="r"){
                initUserInfo()
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(resultCode== Activity.RESULT_OK) when(requestCode){
            RequestCode.GET_IMAGE->{
                var images=data!!.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT)
                path=images[0]
                iv_user_header.setImageURI(DataUtils.getUriFormFile(this,images[0]))
                imageCut(images[0])
            }
            RequestCode.INT_IMAGE_CUT->{
                val bundle = data!!.extras
                var bitmapCut = bundle.getParcelable<Bitmap>("data")
                val baos = ByteArrayOutputStream()
                //compress方法是把一个位图写到一个OutputStream中,参数一是位图对象，二是格式,三是压缩的质量，四是输出流
                bitmapCut.compress(Bitmap.CompressFormat.JPEG, 100, baos)
                //保存到本地
                var save= File(savePath)
                if(!save.exists()){
                    save.createNewFile()
                }
                var out= FileOutputStream(save)
                out.write(baos.toByteArray())
                out.flush()
                out.close()
                iv_user_header.setImageBitmap(BitmapFactory.decodeFile(savePath))

                var bf= BmobFile(save)
                bf.uploadblock(object : UploadFileListener(){
                    override fun done(p0: BmobException?) {
                        p0?:let {
                            saveHeader(bf)
                        }
                        p0?.let {
                            toast("上传头像失败")
                            KLog.e(p0.message.toString())
                        }
                    }
                })


            }
        }

    }

    fun saveHeader(file: BmobFile){
        var my=MyUser()
        my.header= file
        my.update(user!!.objectId,object: UpdateListener(){
            override fun done(p0: BmobException?) {
                p0?:let { toast("更新成功") }
                p0?.let { toast("更新失败")
                    KLog.e(p0.message.toString())
                }
            }
        })
    }


    private fun imageCut(uri: String) {
        try{
            val intent = Intent("com.android.camera.action.CROP")
            intent.setDataAndType(DataUtils.getUriFormFile(this,uri), "image/*")
            // crop为true是设置在开启的intent中设置显示的view可以剪裁
            intent.putExtra("crop", "true")
            // aspectX aspectY 是宽高的比例
            intent.putExtra("aspectX", 1)
            intent.putExtra("aspectY", 1)
            intent.putExtra("outputX", 320)// 输出图片大小
            intent.putExtra("outputY", 320)
            intent.putExtra("return-data", true)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)//添加这一句表示对目标应用临时授权该Uri所代表的文件
            }

            startActivityForResult(intent, RequestCode.INT_IMAGE_CUT)
        }catch (e:Exception){
            KLog.d(e.message.toString())
        }

    }

    override fun onPause() {
        super.onPause()
        if(dialog!=null && dialog!!.isShowing){
            dialog!!.cancel()
        }
    }
}